#include <malloc.h>
#include "stdio.h"

/**
* 如何快速找到未知长度单链表的中间结点
*/

// 定义一个顺序表结构体
typedef struct ListNode{
    char elem;
    struct ListNode *next;
} ListNode;

ListNode *createNode(char data) {
    ListNode *node = (ListNode *) malloc(sizeof(ListNode));
    node->elem = data;
    node->next = NULL;
    return node;
}

ListNode *CreateList(char a[],int length) {
    ListNode *head = createNode(a[0]);
    ListNode *p = head;
    for (int i = 1; i < length - 1; ++i){
        ListNode *node = createNode(a[i]);
        p->next=node;
        node->elem=a[i];
        p = p->next;
    }
    return head;
}

void printLinkList(ListNode *head) {
    int count = 0;
    printf("printLinkList:");
    while (head != NULL) {
        printf("%c", head->elem);
        head = head->next;
        count++;
    }
    printf("\nlist length: %d\n", count);
}

ListNode *findListCenter(ListNode *head) {
    ListNode *center = head;
    ListNode *last= head;
    while(last->next != NULL) {
        if(last->next->next!=NULL) {
            center=center->next;
            last=last->next->next;
        } else {
            break;
        }
    }
    return center;
}


int main() {
    char a[] = "12345678";
    int length = sizeof(a) /sizeof(char);
    ListNode *list = CreateList(a,length);
    printLinkList(list);
    ListNode *center = findListCenter(list);
    printf("%c",center->elem);
    return 0;
}

